﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace PromoOffersCrawler.Crawler.Managers
{
    public class HtmlAnalyzer
    {
        private string htmlContent;

        private HtmlDocument document = new HtmlDocument();

        public string Url { get; private set; }

        public HtmlAnalyzer(string html, string url)
        {
            htmlContent = html;
            Url = url;
            document.LoadHtml(html);
        }

        public HtmlNode GetNode(string tagID)
        {
            var item = document.GetElementbyId(tagID);
            return item;
        }

        public IEnumerable<HtmlNode> GetAllDescedantOf(string tagId, string descedantTagName)
        {
            var item = document.GetElementbyId(tagId);

            if (item == null)
            {
                return null;
            }

            return item.SelectNodes(".//" + descedantTagName);
        }

        public IEnumerable<HtmlNode> GetAllDescedantOf(string rootTagCssClass, string rootTagName, string descedantTagName)
        {
            var item = document.DocumentNode.SelectSingleNode("//" + rootTagName + "[@class='" + rootTagCssClass + "']");

            if (item == null)
            {
                return null;
            }

            return item.SelectNodes(".//" + descedantTagName);
        }

        public bool HasAttribute(HtmlNode node, string attrName, params string[] attrValues)
        {
            return node.Attributes.Any(atr => atr.Name == attrName
                && attrValues.Any(kw => atr.Value.Contains(kw)));
        }


        //public string GetFirstDescedantOf(string rootId, string p2)
        //{

        //}



        internal HtmlNode GetSingleElementByPath(string xpath)
        {
            return this.document.DocumentNode.SelectSingleNode(xpath);
        }
    }
}
